//
//  TabBar.swift
//  MySport
//
//  Created by lanou3g on 16/2/26.
//  Copyright © 2016年 ccsobj. All rights reserved.
//

import UIKit
import SnapKit


private let item_width = UIScreen.mainScreen().bounds.size.width / 5


protocol TabBarDelegate:class{
    func tabBarDidClickMidBtn(tabBar:UITabBar)
}


class TabBar: UITabBar {
    
    weak var clickDelegate:TabBarDelegate?
    lazy var midBtn:UIButton = {
        let midBtn = UIButton()
        return midBtn
    }()
    override init(frame: CGRect) {
        super.init(frame:frame)
        self.tintColor = UIColor.orangeColor()
     self.setupMidBtn(["tabbar_compose_icon_add",
         "tabbar_compose_icon_add_highlighted",
         "tabbar_compose_button",
         "tabbar_compose_button_highlighted"])
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder:aDecoder)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
            self.setupConstract()
    }
    
}

extension TabBar{
///  在tabBar上增加加号按钮，
// @images：加号按钮的普通前景图、高亮前景图，普通背景图、高亮背景图的图片名
    private func setupMidBtn(images:[String]){
        midBtn.setImage(UIImage(named:images[0]), forState:.Normal)
        midBtn.setImage(UIImage(named:images[1]), forState:.Highlighted)
        midBtn.setBackgroundImage(UIImage(named:images[2]), forState:.Normal)
        midBtn.setBackgroundImage(UIImage(named:images[3]), forState:.Highlighted)
        midBtn.addTarget(self, action:"clickMidBtn", forControlEvents:.TouchUpInside)
        self.addSubview(midBtn)
        midBtn.snp_makeConstraints(){[weak self] in
            $0.centerX.equalTo(self!.center.x)
            $0.centerY.equalTo(self!.center.y)
        }
    }
    

    func clickMidBtn(){
        self.clickDelegate?.tabBarDidClickMidBtn(self)
    }
    
/// 为tabBar的所有子视图添加约束
    private func setupConstract(){
        var i:CGFloat = 0.0
        for sub in self.subviews{
            let clazz = NSClassFromString("UITabBarButton")
            if (sub .isKindOfClass(clazz!)) {
                sub.snp_makeConstraints{
                    if i == 2 {i++}
                    $0.left.equalTo(i * item_width)
                    $0.height.equalTo(self.snp_height)
                    $0.bottom.equalTo(self.snp_bottom)
                    $0.width.equalTo(item_width)
                }
                i++
            }
     }
  }
    
}